﻿using LitJson;
using UnityEngine;

namespace CGF
{
    public class Referrer
    {
        public bool success;
        public string content;
    }

    public class GoogleInstallReferrer : MonoBehaviour
    {
        private static GoogleInstallReferrer _instance;
        public static GoogleInstallReferrer Instance
        {
            get
            {
                if (!_instance)
                {
                    _instance = GameObject.FindObjectOfType<GoogleInstallReferrer>();
                    if (!_instance)
                    {
                        GameObject go = new GameObject(nameof(GoogleInstallReferrer));
                        _instance = go.AddComponent<GoogleInstallReferrer>();
                    }
                }
                return _instance;
            }
        }

        private CTask<Referrer> task;
        private AndroidJavaClass jc;

        void Awake()
        {
            if (Application.isPlaying)
            {
                DontDestroyOnLoad(gameObject);
            }
        }

        /// <summary>
        /// 连接Google Play
        /// </summary>
        public async CTask<Referrer> GetInstallReferrer()
        {
            task = CTask<Referrer>.Create();
#if UNITY_ANDROID && !UNITY_EDITOR
            if(jc == null) jc = new AndroidJavaClass("cn.helper.GoogleInstallReferrer");
            jc.CallStatic("startConnect", gameObject.name, "_OnAndroidCallback");
#else
            task.SetResult(new Referrer() { success = false, content = "非Android平台无法获取InstallReferrer" });
#endif
            return await task;
        }

        //必须用public修饰，否则会被混淆，导致回调找不到方法
        public void _OnAndroidCallback(string msg)
        {
            Referrer referrer = JsonMapper.ToObject<Referrer>(msg);
            if (referrer.success)
            {
                if (jc == null) jc = new AndroidJavaClass("cn.helper.GoogleInstallReferrer");
                string installReferrer = jc.CallStatic<string>("getInstallReferrer");
                task.SetResult(JsonMapper.ToObject<Referrer>(installReferrer));
            }
            else
            {
                task.SetResult(referrer);
            }
        }

    }
}